package me.shurufa.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import net.qiujuer.genius.blur.StackBlur;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.utils.ImageUtils;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.ShareConstants;
import me.shurufa.utils.Utils;


public class ShareActivity extends Activity
        implements View.OnClickListener, IWeiboHandler.Response, IUiListener {

    public void ShareActivity() {

    }

    @Bind(R.id.root)
    RelativeLayout mBackground;

    @Bind(R.id.btn_qq)
    LinearLayout shareQQ;

    @Bind(R.id.btn_weixin_circle)
    LinearLayout shareTimeline;

    @Bind(R.id.btn_weixin)
    LinearLayout shareWeixin;

    @Bind(R.id.btn_weibo)
    LinearLayout shareWeibo;

    @Bind(R.id.btn_qzone)
    LinearLayout shareQzone;

    @Bind(R.id.iv_close)
    ImageView cancel;

    // protected View background;


    private String title;

    private String link;

    private String type;

    private String imageUrl;

    private String description;

    private Bitmap image;

    private IWeiboShareAPI mWeiboApi;

    protected SsoHandler mSsoHandler;

    protected IWXAPI mWechatApi;

    private Tencent mTencent;

    private ShareActivity instance;

    private int params;

    private Bitmap mBitmap = null;
    private Bitmap overlay = null;
    private int mWidth;
    private int mHeight;
    private int statusBarHeight;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        ButterKnife.bind(this);
        instance = this;
        //background.setOnClickListener(this);
        cancel.setOnClickListener(this);
        shareQQ.setOnClickListener(this);
        shareTimeline.setOnClickListener(this);
        shareWeixin.setOnClickListener(this);
        shareWeibo.setOnClickListener(this);
        shareQzone.setOnClickListener(this);
        title = getIntent().getStringExtra("title");
        link = "http://www.baidu.com";
        image = getIntent().getParcelableExtra("image");
        imageUrl = "http://img5.duitang.com/uploads/item/201602/23/20160223081717_54zuf.thumb.700_0.jpeg";//getIntent().getStringExtra("imageUrl");
        params = getIntent().getIntExtra("params", 1);
        description = getIntent().getStringExtra("description");
        mWechatApi = WXAPIFactory.createWXAPI(this, ShareConstants.WX_ID);
        // mTencent = Tencent.createInstance(ShareConstants.QQ_ID, getApplicationContext());
//        initWeiBo();
        mWeiboApi = WeiboShareSDK.createWeiboAPI(this, ShareConstants.WB_ID);
        mWeiboApi.registerApp();
        mWeiboApi.handleWeiboResponse(getIntent(), ShareActivity.this);

        // init();
        // mBackground.setBackgroundDrawable(new BitmapDrawable(getResources(), blur(2)));

    }

    public void init() {
        Rect frame = new Rect();
        getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;
        LogUtils.d("EditDigest", "" + statusBarHeight);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay()
                .getMetrics(metrics);
        mWidth = metrics.widthPixels;
        mHeight = metrics.heightPixels;
    }

    private Bitmap blur(int i) {
        long startMs = System.currentTimeMillis();
        // Is scale
        View view = getWindow().getDecorView();

        mBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        Canvas c = new Canvas(mBitmap);
        c.translate(-view.getScrollX(), -view.getScrollY());
        view.draw(c);
        //TODO 去掉通知栏
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        mBitmap = Bitmap.createBitmap(mBitmap, 0, statusBarHeight, width, height - statusBarHeight);
        height -= statusBarHeight;
        float scaleFactor = 8;//缩放比例
        float radius = 8;//模糊程度

        overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(mBitmap, 0, 0, paint);
        //is blur
        // Java
        if (i == 1)
            overlay = StackBlur.blur(overlay, (int) radius, false);
            // Bitmap JNI Native
        else if (i == 2)
            overlay = StackBlur.blurNatively(overlay, (int) radius, false);
            // Pixels JNI Native
        else if (i == 3)
            overlay = StackBlur.blurNativelyPixels(overlay, (int) radius, false);

        LogUtils.d("EditDigestWindow", "blur time is:" + (System.currentTimeMillis() - startMs));
        return overlay;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.background:
                finish();
                break;
            case R.id.btn_weibo:
                shareWeibo();
                finish();
                break;
            case R.id.btn_weixin:
                shareWeChatFriends();
                finish();
                break;
            case R.id.btn_weixin_circle:
                shareWeChatTimeline();
                finish();
                break;
            case R.id.btn_qq:
                shareQQ();
                finish();
                break;
            case R.id.btn_qzone:
                shareQzone();
                finish();
                break;
        }
    }

    private void shareQQ() {
        Bundle b = new Bundle();
        b.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        if (!TextUtils.isEmpty(description)) {
            String s = description;
            if (s.length() > 40) {
                s = description.substring(0, 40);
            }
            b.putString(QQShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(imageUrl)) {
            b.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUrl);
        }
        if (!TextUtils.isEmpty(link)) {
            b.putString(QQShare.SHARE_TO_QQ_TARGET_URL, link);
        }
        b.putString(QQShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        b.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        mTencent.shareToQQ(this, b, this);
    }

    private void shareQzone() {
        Bundle b = new Bundle();
        b.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        if (!TextUtils.isEmpty(description)) {
            String s = description;
            if (s.length() > 40) {
                s = description.substring(0, 40);
            }
            b.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(imageUrl)) {
            ArrayList<String> list = new ArrayList<>();
            list.add(imageUrl);
            b.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, list);
        }
        if (!TextUtils.isEmpty(link)) {
            b.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, link);
        }
        b.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        mTencent.shareToQzone(this, b, this);
    }

    protected void shareWeChatTimeline() {
        shareWeChat(mWechatApi, link, title, description, ImageUtils.getWeChatShareBitmap(image),
                true);
    }

    protected void shareWeChatFriends() {
        shareWeChat(mWechatApi, link, title, description, ImageUtils.getWeChatShareBitmap(image),
                false);
    }

    private void shareWeChat(IWXAPI wechatApi, String url, String title,
                             String description, Bitmap bitmap, boolean isTimeline) {
        if (!wechatApi.isWXAppInstalled()) {
            Toast.makeText(this, "uninstall weixin", Toast.LENGTH_SHORT)
                    .show();
            return;
        } else if (!wechatApi.isWXAppSupportAPI()) {
            Toast.makeText(this, "unsupport weixin", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        if (params == 2) {
            if (isTimeline) {
                msg.title = description;
            } else {
                msg.title = title;
            }

        } else {
            msg.title = description;
        }
        if (description != null) {
            msg.description = description;
        }
        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage" + +System.currentTimeMillis();
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        boolean b = wechatApi.sendReq(req);
    }

    protected void shareWeibo() {
        mWeiboApi = WeiboShareSDK.createWeiboAPI(this, ShareConstants.WB_ID);
        mWeiboApi.registerApp();
        if (!mWeiboApi.isWeiboAppInstalled()) {
            Utils.showToast("uninstall weibo");
            return;
        }
        WeiboMultiMessage multmess = new WeiboMultiMessage();
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = description;
        Bitmap bmp = image;
        mediaObject.setThumbImage(bmp);
        ImageObject object = new ImageObject();
        object.setImageObject(bmp);
        mediaObject.actionUrl = link;
        mediaObject.defaultText = "";
        multmess.imageObject = object;
        multmess.mediaObject = mediaObject;
        SendMultiMessageToWeiboRequest multRequest = new SendMultiMessageToWeiboRequest();
        multRequest.multiMessage = multmess;
        multRequest.transaction = String.valueOf(System.currentTimeMillis());
        mWeiboApi.sendRequest(this, multRequest);
    }

    /*protected void initWeiBo() {
        AuthInfo weiboAuth = new AuthInfo(this, Constants.SinaAppKey,
                Constants.SinaAppRedirectURI, Constants.SinaScope);
        mSsoHandler = new SsoHandler(this, weiboAuth);
    }*/

    /**
     * @see {@link Activity#onNewIntent}
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        mWeiboApi.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        Log.e("baseResponse", "baseResponse" + baseResponse);
        switch (baseResponse.errCode) {


            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, "微博分享成功", Toast.LENGTH_LONG)
                        .show();
                finish();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, "微博分享取消", Toast.LENGTH_LONG)
                        .show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this,
                        "微博分享失败" + ": " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }


    @Override
    public void onComplete(Object o) {
        Toast.makeText(this, "分享成功",
                Toast.LENGTH_SHORT
        )
                .show();
    }

    @Override
    public void onError(UiError uiError) {
        finish();
    }

    @Override
    public void onCancel() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_in_from_bottom);
        // content.startAnimation(animation);
        AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
        animation1.setDuration(200);
        animation1.setFillAfter(true);
        //background.startAnimation(animation1);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

}
